<template>
  <div>
    <el-card shadow="never">
      <template #header>
        <div class="flex justify-between">
          <span class="text-sm">订单统计</span>
          <div>
            <el-check-tag
              :checked="current === item.value"
              style="margin-right: 8px"
              v-for="(item, index) in options"
              :key="index"
              @click="handleChoose(item.value)"
              >{{ item.text }}</el-check-tag
            >
          </div>
        </div>
      </template>

      <div ref="chartRef" id="chart" style="height: 300px; width: 100%"></div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from "vue";
import * as echarts from "echarts";
import { getStatistics3 } from "~/api";
import { useResizeObserver } from "@vueuse/core";
import { entries } from "lodash";

const current = ref("week");
const options = [
  {
    text: "近1个月",
    value: "month",
  },
  {
    text: "近1周",
    value: "week",
  },
  {
    text: "近24小时",
    value: "hour",
  },
];
const chartRef = ref(null);

const handleChoose = (selectedValue) => {};

let myChart = null;
onMounted(() => {
  const chartDom = document.getElementById("chart");
  if (!chartDom) return;
  myChart = echarts.init(chartDom);

  let option = {
    xAxis: {
      type: "category",
      data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        data: [120, 200, 150, 80, 70, 110, 130],
        type: "bar",
        showBackground: true,
        backgroundStyle: {
          color: "rgba(180,180,180,0.2)",
        },
      },
    ],
  };
  // option && myChart.setOption(option);
  myChart.showLoading();
  getStatistics3(current.value)
    .then((res) => {
      option.xAxis.data = res.x;
      option.series[0].data = res.y;
      myChart.setOption(option);
    })
    .catch((err) => console.log(err))
    .finally(() => {
      myChart.hideLoading();
    });
});

// 开发时运行项目bug体现，在打包后会有体现
// 刷新页面图表会有白屏的现象，通过下面方法解决
onBeforeUnmount(() => {
  if (myChart) echarts.dispose(myChart);
});

useResizeObserver(chartRef, (entries) => {
  // const entry = entries[0];
  // const { width, height } = entry.contentRect;
  // text.value = `width: ${width}, height: ${height}`;
  myChart && myChart.resize();
});
</script>
<style lang="scss" scoped></style>
